<template>
  <div class="logs-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>系统日志</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleExportLogs">导出日志</el-button>
            <el-button type="danger" @click="handleCleanLogs">清空日志</el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索和筛选 -->
      <div class="search-filter">
        <el-input v-model="searchQuery" placeholder="搜索日志内容" prefix-icon="Search" style="width: 300px; margin-right: 15px;"></el-input>
        <el-select v-model="selectedLogLevel" placeholder="选择日志级别" style="width: 150px; margin-right: 15px;">
          <el-option label="全部" value=""></el-option>
          <el-option label="INFO" value="INFO"></el-option>
          <el-option label="WARN" value="WARN"></el-option>
          <el-option label="ERROR" value="ERROR"></el-option>
          <el-option label="DEBUG" value="DEBUG"></el-option>
        </el-select>
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="margin-right: 15px;"
        ></el-date-picker>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      
      <!-- 日志表格 -->
      <el-table :data="logsData" style="width: 100%" :row-class-name="getLogLevelClass">
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="timestamp" label="时间" width="180"></el-table-column>
        <el-table-column prop="level" label="级别" width="100">
          <template #default="scope">
            <el-tag :type="getLogLevelType(scope.row.level)">{{ scope.row.level }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" width="150"></el-table-column>
        <el-table-column prop="ip" label="IP地址" width="120"></el-table-column>
        <el-table-column prop="username" label="操作用户" width="120"></el-table-column>
        <el-table-column prop="action" label="操作类型" width="150"></el-table-column>
        <el-table-column prop="content" label="日志内容" min-width="300">
          <template #default="scope">
            <div class="log-content" :title="scope.row.content">
              {{ scope.row.content }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showLogDetails(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 日志详情对话框 -->
    <el-dialog v-model="logDetailsVisible" title="日志详情" width="700px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="日志ID">{{ selectedLog?.id }}</el-descriptions-item>
        <el-descriptions-item label="时间">{{ selectedLog?.timestamp }}</el-descriptions-item>
        <el-descriptions-item label="级别">{{ selectedLog?.level }}</el-descriptions-item>
        <el-descriptions-item label="来源">{{ selectedLog?.source }}</el-descriptions-item>
        <el-descriptions-item label="IP地址">{{ selectedLog?.ip }}</el-descriptions-item>
        <el-descriptions-item label="操作用户">{{ selectedLog?.username }}</el-descriptions-item>
        <el-descriptions-item label="操作类型">{{ selectedLog?.action }}</el-descriptions-item>
        <el-descriptions-item label="日志内容">{{ selectedLog?.content }}</el-descriptions-item>
        <el-descriptions-item label="请求URL">{{ selectedLog?.requestUrl || '-' }}</el-descriptions-item>
        <el-descriptions-item label="请求方法">{{ selectedLog?.requestMethod || '-' }}</el-descriptions-item>
        <el-descriptions-item label="响应状态码">{{ selectedLog?.responseCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="执行耗时">{{ selectedLog?.executionTime || '-' }}ms</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="logDetailsVisible = false">关闭</el-button>
      </template>
    </el-dialog>
    
    <!-- 清空日志确认对话框 -->
    <el-dialog
      v-model="confirmCleanVisible"
      title="确认清空日志"
      width="400px"
      :close-on-click-modal="false"
    >
      <div class="confirm-message">
        <el-alert
          title="警告！"
          description="此操作将清空所有系统日志，且无法恢复。请确认是否继续？"
          type="warning"
          :closable="false"
        ></el-alert>
        <el-input v-model="confirmKeyword" placeholder="请输入 'CONFIRM' 确认清空" style="margin-top: 20px;"></el-input>
      </div>
      <template #footer>
        <el-button @click="confirmCleanVisible = false">取消</el-button>
        <el-button 
          type="danger" 
          @click="handleConfirmClean" 
          :disabled="confirmKeyword !== 'CONFIRM'"
        >
          确认清空
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 搜索和筛选条件
const searchQuery = ref('')
const selectedLogLevel = ref('')
const dateRange = ref([])

// 表格数据
const logsData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 日志详情对话框
const logDetailsVisible = ref(false)
const selectedLog = ref(null)

// 清空日志确认对话框
const confirmCleanVisible = ref(false)
const confirmKeyword = ref('')

// 获取日志级别标签样式
const getLogLevelType = (level) => {
  const typeMap = {
    'INFO': 'info',
    'WARN': 'warning',
    'ERROR': 'danger',
    'DEBUG': 'primary'
  }
  return typeMap[level] || 'default'
}

// 获取日志行样式类名
const getLogLevelClass = ({ row }) => {
  return `log-level-${row.level.toLowerCase()}`
}

// 获取日志列表
const fetchLogs = () => {
  // 实际项目中应该从后端获取数据
  // 这里使用模拟数据
  const mockData = [
    {
      id: 1,
      timestamp: '2023-07-05 15:30:22',
      level: 'INFO',
      source: 'system',
      ip: '192.168.1.100',
      username: 'admin',
      action: 'login',
      content: '用户admin登录成功',
      requestUrl: '/api/auth/login',
      requestMethod: 'POST',
      responseCode: 200,
      executionTime: 125
    },
    {
      id: 2,
      timestamp: '2023-07-05 15:28:45',
      level: 'ERROR',
      source: 'api',
      ip: '192.168.1.101',
      username: 'user123',
      action: 'create',
      content: '创建用户失败：用户名已存在',
      requestUrl: '/api/users',
      requestMethod: 'POST',
      responseCode: 400,
      executionTime: 85
    },
    {
      id: 3,
      timestamp: '2023-07-05 15:25:18',
      level: 'WARN',
      source: 'system',
      ip: '192.168.1.102',
      username: 'admin',
      action: 'update',
      content: '修改系统配置：安全参数已更新',
      requestUrl: '/api/settings/update',
      requestMethod: 'PUT',
      responseCode: 200,
      executionTime: 156
    },
    {
      id: 4,
      timestamp: '2023-07-05 15:20:09',
      level: 'DEBUG',
      source: 'database',
      ip: '127.0.0.1',
      username: 'system',
      action: 'query',
      content: '执行SQL查询：SELECT * FROM users WHERE status = 1',
      requestUrl: '/api/users/query',
      requestMethod: 'GET',
      responseCode: 200,
      executionTime: 45
    },
    {
      id: 5,
      timestamp: '2023-07-05 15:15:33',
      level: 'INFO',
      source: 'system',
      ip: '192.168.1.103',
      username: 'user456',
      action: 'logout',
      content: '用户user456登出系统',
      requestUrl: '/api/auth/logout',
      requestMethod: 'POST',
      responseCode: 200,
      executionTime: 32
    }
  ]
  
  // 应用搜索和筛选
  let filteredData = [...mockData]
  if (searchQuery.value) {
    filteredData = filteredData.filter(log => 
      log.content.includes(searchQuery.value) ||
      log.username.includes(searchQuery.value) ||
      log.ip.includes(searchQuery.value)
    )
  }
  if (selectedLogLevel.value) {
    filteredData = filteredData.filter(log => log.level === selectedLogLevel.value)
  }
  
  total.value = filteredData.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  logsData.value = filteredData.slice(start, end)
}

// 显示日志详情
const showLogDetails = (log) => {
  selectedLog.value = { ...log }
  logDetailsVisible.value = true
}

// 导出日志
const handleExportLogs = () => {
  // 实际项目中应该调用API导出日志
  ElMessageBox.confirm('确定要导出当前筛选条件下的日志吗？', '导出日志', {
    confirmButtonText: '确定',
    cancelButtonText: '取消'
  }).then(() => {
    ElMessage.success('日志导出成功')
  })
}

// 清空日志确认
const handleCleanLogs = () => {
  confirmKeyword.value = ''
  confirmCleanVisible.value = true
}

// 确认清空日志
const handleConfirmClean = () => {
  if (confirmKeyword.value !== 'CONFIRM') {
    return
  }
  
  // 实际项目中应该调用API清空日志
  confirmCleanVisible.value = false
  ElMessage.success('日志已清空')
  fetchLogs()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchLogs()
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = ''
  selectedLogLevel.value = ''
  dateRange.value = []
  currentPage.value = 1
  fetchLogs()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchLogs()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchLogs()
}

// 初始化数据
fetchLogs()
</script>

<style scoped>
.logs-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-filter {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.log-content {
  word-break: break-all;
  white-space: pre-wrap;
  color: #303133;
}

.confirm-message {
  margin-bottom: 10px;
}

/* 日志级别样式 */
:deep(.log-level-error) {
  background-color: #fef0f0;
}

:deep(.log-level-warning) {
  background-color: #fdf6ec;
}

:deep(.log-level-info) {
  background-color: #f0f9ff;
}

:deep(.log-level-debug) {
  background-color: #f5f7fa;
}

@media (max-width: 768px) {
  .search-filter {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-filter .el-input,
  .search-filter .el-select,
  .search-filter .el-date-picker {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>